<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="采集参数" width="1000px" destroyOnClose wrapClassName="modal-params">
    <BasicTable @register="registerTable" ref="selectTable">
      <template #toolbar>
        <a-button type="primary" @click="handleAddLine">绑定属性</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="createActions(record)" />
        </template>
      </template>
    </BasicTable>
    <template #footer>
      <Button type="primary" @click="handleOk">关闭</Button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicTable, useTable, TableAction, EditRecordRow, ActionItem, BasicColumn } from '@/components/Table';
import {
  getDevicePropertyList,
  getDeviceDataTypeList,
  deviceBindParams,
  deleteDeviceBindParams,
  checkDeviceBindParams
} from '@/api/collection/device';
import { getDataTypeListAll } from '@/api/collection/data/index.ts'
import { getUnitListAll } from '@/api/collection/unit'
import { buildUUID } from '@/utils/uuid'

import { ref, createVNode, h } from 'vue';
import { Modal, Button } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { useMessage } from '@/hooks/web/useMessage';

const tableData = ref<Recordable[]>([])

const currentEditKeyRef = ref('');
const deviceId = ref()

const getColumns = (paramsOptions, unitOptions) => {
  return [
    {
      title: '参数属性名称',
      dataIndex: ['dataType', 'id'],
      editRow: true,
      editComponent: 'Select',
      editRule: true,
      editComponentProps: {
        options: paramsOptions,
        fieldNames: {
          label: 'name',
          value: 'id'
        },
        placeholder: '请选择',

      },
      editRender: ({ record }) => {
        return record.name || '--'
      }
    },
    {
      title: '单位',
      dataIndex: ['unit', 'id'],
      editRow: true,
      editComponent: 'Select',
      editRule: true,
      editComponentProps: {
        showSearch: true,
        optionFilterProp: 'name',
        options: unitOptions,
        fieldNames: {
          label: 'name',
          value: 'id'
        },
        placeholder: '请选择',
      },
      editRender: ({ record }) => {
        return record.unit.name || '--'
      }
    },
  ] as BasicColumn[]
}
const { createMessage: msg } = useMessage()
const [registerModal, { closeModal }] = useModalInner(async (data) => {
  deviceId.value = data.record.id;
  const paramsOptions = await getDeviceDataTypeList({ deviceType: data.record.type.code})
  const unitOptions = await getUnitListAll({})
  setColumns(getColumns(paramsOptions, unitOptions))
  getData();
})

const [registerTable, { setLoading, setColumns, deleteTableDataRecord, setPagination }] = useTable({
  canResize: true,
  immediate: true,
  dataSource: tableData,
  columns: getColumns([], []),
  rowKey: 'id',
  actionColumn: {
    width: 150,
    title: '操作',
    dataIndex: 'action',
  },
});

const getData = () => {
  setLoading(true)
  getDevicePropertyList({ deviceId: deviceId.value }).then(res => {
    tableData.value = res
  }).finally(() => {
    setLoading(false)
  })
}

function createActions(record: EditRecordRow): ActionItem[] {
  if (!record.editable) {
    return [
      {
        label: '编辑',
        disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '删除',
        color: 'error',
        disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
        onClick: hancleCheckDelete.bind(null, record),

      },
    ];
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record),
    },
    {
      label: '取消',
      onClick: handleCancel.bind(null, record),
    },
  ];
}

const handleAddLine = () => {
  const newLine = { id: buildUUID(), isNew: true, editable: true, dataType: { id: undefined }, unit: { id: undefined } }
  setPagination({ current: 1 })
  tableData.value.unshift(newLine)
}

const handleEdit = (record) => {
  currentEditKeyRef.value = record.key;
  record.onEdit?.(true);
}

const handleDelete = (id) => {
  deleteDeviceBindParams({ id }).then(res => {
    deleteTableDataRecord(id)
    msg.success('删除成功')
  })
}

const hancleCheckDelete = async (record) => {
  if (record.isNew) {
    Modal.confirm({
      title: '是否删除',
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        deleteTableDataRecord(record.id)
        msg.success('删除成功')

      },
      onCancel() {
      },
    })
    return
  }
  const data = await checkDeviceBindParams({ id: record.id })
  const hasRelationStr = !data ? '数据正在采集中，请确认' : ''
  Modal.confirm({
    title: '是否删除',
    icon: createVNode(ExclamationCircleOutlined),
    content: h('div', { style: 'color:red;' }, hasRelationStr),
    onOk() {
      handleDelete(record.id)
    },
    onCancel() {
    },
  })
  return
}

const handleCancel = (record: EditRecordRow) => {
  currentEditKeyRef.value = '';
  record.onEdit?.(false, false);
}

const handleSave = async (record: EditRecordRow) => {
  // 校验
  const valid = await record.onValid?.();
  if (valid) {
    const editData = cloneDeep(record.editValueRefs)!;
    let data: any = {
      deviceId: deviceId.value,
      unitId: editData['unit,id'],
      dataTypeId: editData['dataType,id']
    }
    if (!record.isNew) {
      data.id = record.id
    }
    await deviceBindParams(data)

    const pass = await record.onEdit?.(false, true);
    if (pass) {
      currentEditKeyRef.value = '';
    }
    msg.success({ content: '数据已保存', key: 'saving' });
    getData()
  } else {
    msg.error({ content: '请填写正确的数据', key: 'saving' });
  }
}
const handleOk = () => {
  let hasEditing = tableData.value.some(item => item.editable)
  if (hasEditing) {
    Modal.confirm({
      title: '提示',
      icon: createVNode(ExclamationCircleOutlined),
      content: '当前还有未保存的数据，确认关闭吗？',
      onOk() {
        handleClose()
      },
      onCancel() {
        return
      },
      class: 'test',
    })
    return
  }
  handleClose()
};

const handleClose = () => {
  tableData.value = []
  closeModal()
}

</script>
<style lang="scss">
.modal-params {
  .ant-modal {
      height: 80vh;
    }
}
</style>
